package cn.zmwh.im.server.netty;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.zmwh.im.server.constant.IMRedisKey;
import cn.zmwh.im.server.utils.IdGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.List;

@Slf4j
@Component
@AllArgsConstructor
public class IMServerGroup implements CommandLineRunner {

    public static volatile long serverId = 0;

    private final RedisTemplate redisTemplate;

    private final List<IMServer> imServers;

    /***
     * 判断服务器是否就绪
     *
     **/
    public boolean isReady() {
        for (IMServer imServer : imServers) {
            if (!imServer.isReady()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void run(String... args) {
        // 初始化SERVER_ID
        String key = IMRedisKey.SERVER_INCR_ID;
        serverId = redisTemplate.opsForValue().increment(key, 1);
        // 启动服务
        for (IMServer imServer : imServers) {
            imServer.start();
        }


        // 从配置文件读取 workerId 和 dataCenterId
        long dataCenterId = 0;
        if (serverId > 30) {
            log.error("服务器ID不能大于30");
            dataCenterId = RandomUtil.randomInt(0, 32);
            redisTemplate.delete(IMRedisKey.SERVER_INCR_ID);
        }
        Snowflake snowflake = IdUtil.getSnowflake(serverId, dataCenterId);
        IdGenerator.init(snowflake);
    }

    @PreDestroy
    public void destroy() {
        // 停止服务
        for (IMServer imServer : imServers) {
            imServer.stop();
        }
    }

}
